package wsz.rpc.provider.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import wsz.rpc.zk.ZkServer;

/**
 * @author wsz
 * @date 2021/11/30 17:14
 **/
@Service
public class RpcServer implements DisposableBean {

    private NioEventLoopGroup bossGroup;
    private NioEventLoopGroup workGroup;

    @Value("${zkServerUrl}")
    private String zkServerUrl;

    private ZkServer server;
    private String nettyHost;
    private int nettyPort;

    @Autowired
    private RpcServerHandler rpcServerHandler;

    public void startServer(String nettyHost, int nettyPort) {
        try {
            // 注册zk
            this.nettyHost = nettyHost;
            this.nettyPort = nettyPort;
            registryZk();

            bossGroup = new NioEventLoopGroup(1);
            workGroup = new NioEventLoopGroup();

            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new StringDecoder());
                            pipeline.addLast(new StringEncoder());
                            pipeline.addLast(rpcServerHandler);
                        }
                    });
            ChannelFuture future = bootstrap.bind(nettyHost, nettyPort).sync();
            future.addListener(future1 -> {
                if (future1.isSuccess()) {
                    System.out.println("startServer端口绑定成功:" + nettyHost +"_" + nettyPort);
                } else {
                    System.out.println("端口绑定失败");
                }
            });
            System.out.println("----服务端启动成功----");
            future.channel().closeFuture().sync();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            server.closeServer();
            shutGroup();
        }
    }

    private void registryZk() throws Exception {
        server = new ZkServer(zkServerUrl, nettyHost + ":" +nettyPort);
    }

    private void shutGroup() {
        if (bossGroup != null) {
            bossGroup.shutdownGracefully();
        }
        if (workGroup != null) {
            workGroup.shutdownGracefully();
        }
    }

    @Override
    public void destroy() throws Exception {
        shutGroup();
    }
}
